<?php
class Api_Lib_Rsp_Sample_Chuku {

    function __construct() {
        $this->_modelExample = FLEA::getSingleton('Model_Sample_Chuku');
        $this->_subModel = FLEA::getSingleton('Model_Sample_Chuku2Product');
    }

    /**
     * 更新入库/插入库
     * Time：2019/11/11 10:31:54
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function updateSample($params,& $service){
        if($params['formData']){
            $formData = json_decode($params['formData'] ,1);
            $formData['creater'] = $params['creater'];
        }
        // 先验证参数
        $ruleRequired = array('employId');
        foreach ($ruleRequired as $key => & $v) {
            if(!isset($formData[$v]) || !$formData[$v]){
                $service->send_user_error($v."参数必填");
            }
        }

        //有些方法在controller中，这里调用
        $ctl = FLEA::getSingleton('Controller_Sample_Chuku');
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');

        // 如果有id,表示是修改，需要先获取原来的数据
        $chuku = array();

        //组织数据
        $data = array();
        $data['id']        = $formData['id'] + 0;
        $data['clientId']  = $formData['clientId'] + 0;
        $data['employId']  = $formData['employId'] + 0;
        $data['chukuCode'] = $formData['chukuCode'] ? $formData['chukuCode'] : $ctl->createNewCode();
        $data['chukuDate'] = $formData['chukuDate'] ? $formData['chukuDate'] : date('Y-m-d');
        $data['reason']    = strval($formData['reason']);
        $data['memo']      = strval($formData['memo']);
        $data['creater']   = strval($formData['creater']);

        //处理入库明细的信息
        $error = '';
        foreach ($formData['Products'] as $key => & $v) {
            //如果没有数量或者材料Id,则跳过
            if(!$v['productId']){
                unset($formData['Products'][$key]);
            }
            if(!$v['cnt']){
                $error = '第'.($key+1).'行,数量必填且大于0';

            }
            if($v['kucun'] && $v['cnt'] > $v['kucun']){
                $error = '第'.($key+1).'行有误，出库数量不能大于库存数量';
            }

            //查找入库的信息，通过code
            $sql = "SELECT count(*) as cnt from sample_ruku2product where productId='{$v['productId']}' and kuweiId='{$v['kuweiId']}' and code='{$v['code']}' and type='{$v['type']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            if(!$tmp[0]['cnt']){
                $error = '产品信息和条码信息不匹配';
            }

            // 通过条码，获取最近一次的格型等信息
            if($v['code']){
                $sql = "SELECT * from sample_ruku2product where code='{$v['code']}' order by id desc limit 0,1";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['gexing'] = $tmp[0]['gexing'];
                $v['zuzhi']  = $tmp[0]['zuzhi'];
                $v['tanli']  = $tmp[0]['tanli'];
                $v['hzlId']  = $tmp[0]['hzlId'];
            }

            //判断库存
            //查找库存数量，判断出库数量是否合理
            // $kucun = $modelKucun->getKucun(array(
            //     'productId' =>$v['productId'],
            //     'kuweiId'   =>$v['kuweiId'],
            //     'type'      =>$v['type'],
            //     'proDesc'   =>$v['proDesc'],
            // ));
            // if($kucun <= 0 || $kucun < $v['cnt']){
            //     $error = '库存不够';
            // }

            if($error){
                break;
            }
        }
        //把错误返回给前端
        if($error){
            return array('success'=>false ,'msg'=>$error);
        }

        if(!$formData['Products']){
            return array('success'=>false ,'msg'=>'无有效明细信息');
        }

        //出库明细
        $data['Products'] = $formData['Products'];

        $result = $this->_modelExample->save($data);

        return array('success'=>$result ? true : false ,'msg'=>'保存完成');
    }

    /**
     * getRukuList
     * Time：2019/11/11 15:11:10
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function getChukuList($params,& $service){
        $pageNum     = $params['pageNum'] ? $params['pageNum'] : 20;
        $currentPage = $params['page'] ? $params['page'] : 1;

        $sql="SELECT x.*,y.chukuDate,y.chukuCode,y.reason,y.creater,y.employId,y.clientId
              from sample_chuku2product x
              left join sample_chuku y on y.id=x.chukuId
              where 1 ";

        if($params['chukuCode']!='') {
            $sql.=" and y.chukuCode like '%{$params['chukuCode']}%'";
        }
        if($params['clientId']) {
            $sql.=" and y.clientId = '{$params['clientId']}'";
        }
        if($params['employId']) {
            $sql.=" and y.employId = '{$params['employId']}'";
        }
        if($params['type']) {
            $sql.=" and x.type = '{$params['type']}'";
        }
        if($params['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$params['proDesc']}%'";
        }
        if($params['code']!='') {
            $sql.=" and x.code like '%{$params['code']}%'";
        }
        if($params['reason']!='') {
            $sql.=" and y.reason like '%{$params['reason']}%'";
        }
        if($params['productId']) {
            $sql.=" and x.productId = '{$params['productId']}'";
        }
        if($params['kuweiId']) {
            $sql.=" and x.kuweiId = '{$params['kuweiId']}'";
        }
        if($params['dateFrom']){
            $sql .= " and y.chukuDate >= '{$params['dateFrom']}' and y.chukuDate <= '{$params['dateTo']}'";
        }
        $sql .=" order by y.id desc,x.id asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pageNum ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelClient = FLEA::getSingleton('Model_Jichu_Client');
        $modelEmploy = FLEA::getSingleton('Model_Jichu_Employ');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $v['sid'] = $v['id'];
            unset($v['id']);

            //产品明细
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $_tRow = array();
            $modelProduct->filedValue3($_tRow ,$tmp[0] ,$filedsSingle);
            $v['productDesc'] = $_tRow;
            // $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'text','' ,$filedsDefault);
            foreach ($_tRow as $tk => & $desc) {
                $v['otherDesc'][] = $tk.':'.$desc;
                $v['others'][] = array('title'=>$tk  ,'value'=>$desc);
            }
            $v['othersRows'] = ceil(count($v['others'])/2);//用户计算显示其他信息的行数

            $v['cnt'] = round($v['cnt'],6);
            $v['price'] = round($v['price'],6);

            if($v['kuweiId']){
                $_tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $_tmp['kuweiName'];
            }

            if($v['clientId']){
                $_tmp = $modelClient->find($v['clientId']);
                $v['clientName'] = $_tmp['compName'];
            }

            if($v['employId']){
                $_tmp = $modelEmploy->find($v['employId']);
                $v['employName'] = $_tmp['employName'];
            }

            // 后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }
        }

        return array('row'=>$rowset,'page'=>$currentPage,'total'=>$pager->totalCount,'pageCount'=>count($rowset));
    }

    /**
     * 查询明细
     * Time：2019/11/11 15:50:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function getChukuInfo($params,& $service){
        if(!intval($params['id'])){
            $service->send_user_error('id not found');
        }
        $params['id'] = intval($params['id']);
        //查找数据
        $info = $this->_modelExample->find($params['id']);
        if(!$info['id']){
            $service->send_user_error('id not in database');
        }

        $modelClient = FLEA::getSingleton('Model_Jichu_Client');
        $modelEmploy = FLEA::getSingleton('Model_Jichu_Employ');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelProduct= FLEA::getSingleton('Model_Jichu_Product');
        if($info['clientId']){
            $_tmp = $modelClient->find($info['clientId']);
            $info['clientName'] = $_tmp['compName'];
        }
        if($info['employId']){
            $_tmp = $modelEmploy->find($info['employId']);
            $info['employName'] = $_tmp['employName'];
        }

        //获取产品信息
        foreach ($info['Products'] as $key => & $v) {
            if($v['productId']){
                $sql = "SELECT x.*,y.kindName from jichu_product x
                    left join jichu_prokind y on x.kindId=y.id
                  where x.id = '{$v['productId']}'";
                $_tmp = $modelProduct->findBySql($sql);
                $_tmp = $_tmp[0];
                $_tRow = array();
                $modelProduct->filedValue3($_tRow ,$_tmp);
                $_tmp['otherDesc'] = $_tRow;

                $v['proCode'] = $_tmp['proCode'];
                $v['proName'] = $_tmp['proName'];
                $v['kindName'] = $_tmp['kindName'];
                $v['Product'] = $_tmp;
            }

            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }

            if($v['kuweiId']){
                $_tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $_tmp['kuweiName'];
            }
            //查找库存情况
            $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
            $v['kucun'] = $modelKucun->getKucun(array(
                'productId' =>$v['productId'],
                'kuweiId'   =>$v['kuweiId'],
                'type'      =>$v['type'],
                'proDesc'   =>$v['proDesc'],
                'code'      =>$v['code'],
            ));
            $v['kucun'] = round($v['kucun'],3);
            $v['cnt'] = round($v['cnt'],6);
            $v['price'] = round($v['price'],6);
        }

        return $info;
    }

    /**
     * 删除
     * Time：2019/11/11 15:50:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function chukuRemove($params,& $service){
        if(!intval($params['id'])){
            $service->send_user_error('params id not found');
        }
        $params['id'] = intval($params['id']);

        $info = $this->_modelExample->find($params['id']);
        if(!$info['id']){
            $service->send_user_error('id not in database');
        }

        //查找还有多少个明细信息
        $res = $this->_modelExample->removeByPkv($info['id']);

        return array('success'=>$res ? true : false ,'msg'=>'操作完成');
    }

    /**
     * 删除
     * Time：2019/11/11 15:50:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function chukuRemoveSon($params,& $service){
        if(!intval($params['sid'])){
            $service->send_user_error('sid not found');
        }
        $params['sid'] = intval($params['sid']);

        $info = $this->_subModel->find($params['sid']);
        if(!$info['id']){
            $service->send_user_error('sid not in database');
        }

        //查找还有多少个明细信息
        $count = $this->_subModel->findCount(array('chukuId'=>$info['chukuId']));
        if($count == 1){
            $res = $this->_modelExample->removeByPkv($info['chukuId']);
        }else{
            $res = $this->_subModel->removeByPkv($params['sid']);
        }

        return array('success'=>$res ? true : false ,'msg'=>'操作完成');
    }

}

?>